const DeployLog = require('../models/deploy-log.model');
const Project = require('../models/project.model');
const deployService = require('../services/deploy.service');
const webSocketService = require('../services/websocket.service');

// 在部署完成时更新项目统计数据
const updateProjectStats = async (projectId, status) => {
  const updateData = {
    $inc: {
      'deployStats.totalCount': 1,
      [`deployStats.${status === 'success' ? 'successCount' : 'failedCount'}`]: 1
    },
    lastDeployTime: new Date()
  };
  
  await Project.findByIdAndUpdate(projectId, updateData);
};

exports.startDeploy = async (req, res) => {
  try {
    const project = await Project.findById(req.params.projectId);
    if (!project) {
      return res.status(404).json({ error: '项目不存在' });
    }

    const deployLog = new DeployLog({
      projectId: project._id,
      branch: project.deploymentConfig.branch,
      deployedBy: req.user._id,
      status: 'running',
      logs: []
    });
    await deployLog.save();

    // 更新项目状态并通知
    project.status = 'deploying';
    await project.save();
    webSocketService.sendDeployStatus(project._id.toString(), 'deploying');

    // 异步执行部署
    deployService.startDeploy(project, deployLog)
      .then(async () => {
        // 部署成功时更新统计
        await updateProjectStats(project._id, 'success');
        project.status = 'success';
        await project.save();
        webSocketService.sendDeployStatus(project._id.toString(), 'success');
      })
      .catch(async (error) => {
        // 部署失败时更新统计
        await updateProjectStats(project._id, 'failed');
        project.status = 'failed';
        await project.save();
        webSocketService.sendDeployStatus(project._id.toString(), 'failed');
        console.error('部署失败:', error);
      });

    res.json({ message: '部署已开始', deployLog });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

exports.getProjectDeployLogs = async (req, res) => {
  try {
    const logs = await DeployLog.find({ projectId: req.params.projectId })
      .sort({ startTime: -1 })
      .populate('projectId', 'name repositoryUrl status')
      .populate('deployedBy', 'username')
      .limit(10);
    res.json(logs);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

exports.getAllDeployLogs = async (req, res) => {
  try {
    const logs = await DeployLog.find()
      .sort({ startTime: -1 })
      .populate('projectId', 'name repositoryUrl status')
      .populate('deployedBy', 'username')
      .limit(20);

    // 格式化响应数据
    const formattedLogs = logs.map(log => ({
      ...log.toObject(),
      project: log.projectId
    }));

    res.json(formattedLogs);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

exports.rollback = async (req, res) => {
  try {
    const project = await Project.findById(req.params.projectId);
    if (!project) {
      return res.status(404).json({ error: '项目不存在' });
    }

    const targetDeployLog = await DeployLog.findById(req.params.deployId);
    if (!targetDeployLog) {
      return res.status(404).json({ error: '部署记录不存在' });
    }

    if (targetDeployLog.status !== 'success') {
      return res.status(400).json({ error: '只能回滚到成功的部署版本' });
    }

    // 更新项目状态
    project.status = 'deploying';
    await project.save();

    // 异步执行回滚
    deployService.rollback(project, targetDeployLog)
      .catch(error => {
        console.error('回滚失败:', error);
      });

    res.json({ message: '回滚已开始' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
}; 